package com.niiwoo.civet.account.service.dubbo.refund;

import com.alibaba.dubbo.config.annotation.Service;
import com.dangdang.ddframe.rdb.sharding.api.HintManager;
import com.dangdang.ddframe.rdb.sharding.hint.HintManagerHolder;
import com.niiwoo.civet.account.dto.common.AccountBatchTransOrderDTO;
import com.niiwoo.civet.account.dto.common.AsyncTransactionNotifyDTO;
import com.niiwoo.civet.account.enums.CanRefundEnum;
import com.niiwoo.civet.account.enums.OrderEndTypeEnum;
import com.niiwoo.civet.account.enums.RefundStatusEnum;
import com.niiwoo.civet.account.service.AccountRefundOrderPushDubboService;
import com.niiwoo.civet.account.service.local.refund.CommonToolsService;
import com.niiwoo.civet.account.service.local.refund.QueryRefundTransationLocalService;
import com.niiwoo.civet.account.service.local.refund.newRefund.AccountRefundProcessAutoLocalService;
import com.niiwoo.civet.account.service.local.refund.newRefund.AccountRefundProcessLocalService;
import com.niiwoo.civet.account.service.local.refund.newRefund.CallBackRefundLocalService;
import com.niiwoo.civet.account.service.local.refund.newRefund.RefundQueryLocalService;
import com.niiwoo.civet.base.enums.RefundBizStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.FastDateFormat;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 还款订单推送服务
 * Created by fushengcai on 2017/11/9.
 */
@Slf4j
@Service(version = "1.0.0")
public class AccountRefundOrderPushDubboServiceImpl implements AccountRefundOrderPushDubboService {

    @Autowired
    private QueryRefundTransationLocalService queryRefundTransationLocalService;
    @Autowired
    private AccountRefundProcessLocalService accountRefundWithResponseLocalService;
    @Autowired
    private CallBackRefundLocalService callBackRefundLocalService;
    @Autowired
    private RefundQueryLocalService refundQueryLocalService;
    @Autowired
    private AccountRefundProcessAutoLocalService accountRefundProcessJobLocalService;
    @Autowired
    private CommonToolsService commonToolsService;

    /**
     * 按指定还款号同步状态(web)
     * @param batchNo
     */
    @Override
    public void syncTransationStatuByBatchNo(String batchNo){
//        //commonToolsService.rollBackForGuaranteeAccount();
//        Assert.notNull(batchNo,"批次号不可空");
//        queryRefundTransationLocalService.syncTransationStatuByBatchNoNew(batchNo);
//        //callBackRefundLocalService.completJobForBill();
    }

    /**
     * 默认查询24小以内，且30分钟以上还在处理中的
     * 同步所有还款状态
     */
    @Override
    public void syncTransationStatuAll(){
//        log.info("syncTransationStatuAll 72小时内");
//        String startTime = FastDateFormat.getInstance("YYYY-MM-dd HH:mm:ss").format(new DateTime(new Date()).plusHours(-72).toDate());
//        String endTime = FastDateFormat.getInstance("YYYY-MM-dd HH:mm:ss").format(new DateTime(new Date()).plusMinutes(-10).toDate());
//        queryRefundTransationLocalService.syncTransationStatuAll(startTime,endTime);
    }



    /**
     * 还款前置处理开始
     * 自动还款（JOB）
     * @param dtoList    还款交易订单列表
     * @param isWithHold
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public void pushTransOrderNew(List<AccountBatchTransOrderDTO> dtoList, boolean isWithHold) throws ExecutionException, InterruptedException {
//        Assert.notEmpty(dtoList, "还款订单不可空");
//        dtoList.forEach(dto -> {
//            Assert.notNull(dto, "还款订单不可空");
//            Assert.notNull(dto.getBatchRequestNo(), "请求流水号不可为空");
//            Assert.notNull(dto.getProjectId(), "标的ID不可为空");
//            Assert.notNull(dto.getAmount(), "应还款金额不可为空");
//            Assert.notNull(dto.getCurrentPeriod(), "当前期数不可为空");
//            Assert.notNull(dto.getTotalPeriod(), "总期数不可为空");
//            Assert.notNull(dto.getProjectTitle(), "标的名称不可为空");
//            Assert.notNull(dto.getBorrowerUserId(), "借款人ID不可为空");
//        });
//        if (!HintManagerHolder.isMasterRouteOnly()) {
//            HintManagerHolder.clear();
//            HintManager hintManager = HintManager.getInstance();
//            hintManager.setMasterRouteOnly();
//        }
//        //保存还款订单
//        accountRefundWithResponseLocalService.pushTransOrder(dtoList, isWithHold);
    }


    /**
     * web还款
     * @param dto
     * @param isNeedWithhold
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public RefundBizStatusEnum pushTransOrderSyncNew(AccountBatchTransOrderDTO dto, boolean isNeedWithhold) throws ExecutionException, InterruptedException {
//        Assert.notNull(dto, "还款订单不可空");
//        Assert.notNull(dto.getBatchRequestNo(), "请求流水号不可为空");
//        Assert.notNull(dto.getProjectId(), "标的ID不可为空");
//        Assert.notNull(dto.getAmount(), "应还款金额不可为空");
//        Assert.notNull(dto.getCurrentPeriod(), "当前期数不可为空");
//        Assert.notNull(dto.getTotalPeriod(), "总期数不可为空");
//        Assert.notNull(dto.getProjectTitle(), "标的名称不可为空");
//        Assert.notNull(dto.getBorrowerUserId(), "借款人ID不可为空");
//        //保存还款订单
//        log.info("account center pushTransOrderAppSync init-------");
//        if (!HintManagerHolder.isMasterRouteOnly()) {
//            HintManagerHolder.clear();
//            HintManager hintManager = HintManager.getInstance();
//            hintManager.setMasterRouteOnly();
//        }
//        return accountRefundWithResponseLocalService.pushTransOrderSync(dto,isNeedWithhold);
        return null;
    }

    /**
     * 还款回调
     * @param list
     */
    @Override
    public void refundCallBackNew(List<AsyncTransactionNotifyDTO> list) {
//        Assert.notEmpty(list, "还款结果集合不可空");
//        callBackRefundLocalService.refundCallBack(list);
    }


    /**
     * 还款补单
     */
    @Override
    public void complateRefund() throws ExecutionException, InterruptedException {
//        CompletableFuture.runAsync(new Runnable() {
//            @Override
//            public void run() {
//                log.info("handBatchOrderFailWithhold-start-");
//                accountRefundProcessJobLocalService.handBatchOrderFailWithhold();
//            }
//        });
//        accountRefundProcessJobLocalService.completedRefundJob();
    }

    @Override
    public CanRefundEnum checkProjectCanRefundByType(Long projectId, Integer currentPeriod,Byte type) {
//        Assert.notNull(projectId, "projectId不可空");
//        return refundQueryLocalService.checkProjectCanRefund(projectId, currentPeriod, type);
        return null;
    }

    /**
     * 还款预处理回退
     * @return
     */
    @Override
    public boolean rollbackProtransaction(Long proTransactionOrderId){
//        Assert.notNull(proTransactionOrderId,"订单号不可空");
//        Assert.isTrue(proTransactionOrderId>0,"订单号不可为0");
//        return accountRefundProcessJobLocalService.rollbackProTransaction(proTransactionOrderId);
        return false;
    }
    /**
     * 代扣(神盾)
     *
     * @param withholdOrderId
     * @param status
     * @param endType
     */
    @Override
    public void complementWithhold(Long withholdOrderId, RefundStatusEnum status, OrderEndTypeEnum endType) {
//        Assert.notNull(withholdOrderId, "withholdOrderId不可空");
//        Assert.notNull(status, "status不可空");
//        Assert.notNull(endType, "endType不可空");
//        accountRefundProcessJobLocalService.complementWithhold(withholdOrderId, status, endType);
    }


}
